package com.jz.pay.utils.lock;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;

import java.util.concurrent.TimeUnit;

public class RedisLock {

    /**
     * Redission客户端，可以用来做分布式锁，初始化了
     */
    private static RedissonClient redissonClient;

    private final RLock rLock;

    private RedisLock(RLock rLock){
        this.rLock = rLock;
    }

    public static void setRedissonClient(RedissonClient redissonClient) {
        if(RedisLock.redissonClient == null){
            RedisLock.redissonClient = redissonClient;
        }
    }

    public static RedisLock lock(String key){
        RLock rLock =  redissonClient.getLock(key);
        try {
            if(rLock.tryLock(20,25, TimeUnit.SECONDS)){
                System.out.println("获取到了锁");
                return new RedisLock(rLock);
            }
        } catch (InterruptedException e) {
            System.out.println("获取锁失败");
            e.printStackTrace();
        }
        throw new RuntimeException("获取锁超时");
    }

    public void unlock(){
        this.rLock.unlock();
    }

}
